package cate.game.activity.rank;

import cate.common.table.activity.rankactivity.row.RankActivityBaseRow;
import cate.common.table.activity.rankactivity.row.RankActivityRewardRow;
import cate.common.table.d.GDOperation;
import cate.game.mail.po.MailBuilder;
import cate.game.rank.h.ConditionRankHandler;
import cate.game.rank.h.IConditionRankHandler;
import cate.game.rank.po.Rank;
import cate.game.rank.po.RankSPO;
import cate.game.res.MixRes;
import cate.game.role.mail.Mail;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public abstract class BaseRankActivityHandler extends ConditionRankHandler<RankSPO<Rank>, Rank> implements IConditionRankHandler {
    @Override
    protected RankSPO createSPO() {
        return new RankSPO();
    }

    public void sendReward(RankActivityBaseRow baseRow){
        if(baseRow == null || baseRow.mailId == 0){
            log.info("排行榜活动{}结束拉，但是没有配置邮件id，不发奖拉", baseRow==null ? 0:baseRow.funcId);
            return;
        }
        for(int i = 0, len = getRankList(null).size(); i < len; ++i){
            RankActivityRewardRow rewardRow = gameBody.table.rankActivity.reward.getRewardRow(baseRow.group, i);
            if (rewardRow != null && StringUtils.isNotBlank(rewardRow.rewardStr)) {
                Rank rank = getDataByIndex(null, i);
                if(rank != null){
                    MixRes reward = new MixRes(rewardRow.rewardStr);
                    long extraValue = getExtraValue(rank);
                    if(StringUtils.isNotBlank(rewardRow.extraRewardStr) && extraValue >= rewardRow.extraValue){
                        reward.addList(new MixRes(rewardRow.extraRewardStr));
                    }
                    List<Object> params = new ArrayList<>();
                    params.add(i + 1);
                    Mail mail = new MailBuilder()
                            .setContentId(baseRow.mailId)
                            .setParamList(params)
                            .setReward(reward)
                            .setOperation(GDOperation.RANK_ACTIVITY_REWARD)
                            .setOperationSub(i + 1)
                            .build();
                    log.info("排行榜活动{}发送邮件，第{}名:{}, value:{}, extraValue:{}, 上榜时间:{}", baseRow.funcId, i+1,rank.owner.base.name, rank.value, extraValue, rank.recordTime);
                    gameBody.mail.send(rank.owner.uid, mail);
                }
            }
        }
        this.clearList();
        save();
    }

    protected long getExtraValue (Rank rank) {
        return rank.value;
    }
}
